package com.ruoyi.biz.service;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.domain.BizPwd;
import com.ruoyi.biz.mapper.BizPwdMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;

import java.util.Arrays;

import com.ruoyi.common.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.biz.mapper.BizPwdTypeMapper;
import com.ruoyi.biz.domain.BizPwdType;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 密码类型Service业务层处理
 *
 * @author tianl
 * @date 2025-02-08
 */
@Service
public class BizPwdTypeService extends ServiceImpl<BizPwdTypeMapper, BizPwdType> {
    @Autowired
    private BizPwdMapper bizPwdMapper;

    /**
     * 分页查询密码类型
     */
    public IPage<BizPwdType> listPage(BizPwdType req) {
        return baseMapper.list(PageUtils.page(), req);
    }

    /**
     * 查询密码类型列表
     */
    public List<BizPwdType> list(BizPwdType req) {
        return baseMapper.list(req);
    }

    /**
     * 根据ID查询
     */
    public BizPwdType selectById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 新增修改密码类型
     */
    @Transactional(rollbackFor = Exception.class)
    public void beforeSave(BizPwdType bizPwdType) {
        if (bizPwdType.getId() != null) {
            bizPwdType.setUpdateTime(DateUtils.getNowDate());
        } else {
            bizPwdType.setCreateTime(DateUtils.getNowDate());
            bizPwdType.setUpdateTime(DateUtils.getNowDate());
        }
        saveOrUpdate(bizPwdType);
    }

    /**
     * 批量删除密码类型
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Long> ids) {
        LambdaQueryWrapper<BizPwd> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(i -> i.in(BizPwd::getTypeId, ids));
        long count = bizPwdMapper.selectCount(wrapper);
        if (count > 0) {
            throw new ServiceException("分类下存在密码信息，请先删除密码信息");
        }
        LambdaQueryWrapper<BizPwdType> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.and(i -> i.in(BizPwdType::getParentId, ids));
        long count2 = baseMapper.selectCount(wrapper2);
        if (count2 > 0) {
            throw new ServiceException("分类下存在子级，请先删除子级");
        }
        return baseMapper.deleteBatchIds(ids);
    }

}
